const fs = require('fs');
const { resolve, join } = require('path');
const prettier = require('prettier');

const hash = (str) => str.replace(/\-|\%|\d|\.|\/|\\|\:/g, '_');

const paths = ['blocks', 'templates', 'cards'];

const generateConfig = () => {
  console.log('自动生成配置文件')
  const imgImports = [];
  let imgFileContent = '';
  const configFilePath = resolve(__dirname, '../src/_config');
  if (!fs.existsSync(configFilePath)) {
    fs.mkdirSync(configFilePath);
  }
  if (!fs.existsSync(join(configFilePath, 'images'))) {
    fs.mkdirSync(join(configFilePath, 'images'))
  }
  paths.forEach(target => {
    const result = [];
    const targetPath = resolve(__dirname, `../${target}`);
    const blocks = fs.readdirSync(targetPath);

    blocks.forEach((block) => {
      if (block.startsWith('.')) {
        return;
      }
      const blockPath = join(targetPath, block, 'package.json')
      const pkg = JSON.parse(fs.readFileSync(blockPath, 'utf-8'));
      if (pkg.block && pkg.block.category) {
        const info = {
          type: target,
          block,
          category: pkg.block.category,
          routePath: `/${target}/${block}`,
        }
        const imgPath = resolve(targetPath, block, 'snapshot.png');
        if (fs.existsSync(imgPath)) {
          const imageName = hash(imgPath);
          info.img = imageName;
          imgImports.push(imageName);
          fs.writeFileSync(join(configFilePath, 'images', `${imageName}.png`), fs.readFileSync(imgPath, 'binary'), 'binary')
        }
        result.push(info);
      }
    })

    const jsonContent = prettier.format(JSON.stringify(result), { parser: 'json' })

    fs.writeFileSync(`${configFilePath}/${target}-config.json`, jsonContent, 'utf8');
  });

  imgImports.forEach(name => {
    imgFileContent += `import ${name} from './images/${name}.png';`
  })

  imgFileContent += 'export default {'
  imgImports.forEach(name => {
    imgFileContent += `['${name}']: ${name},`;
  })
  imgFileContent += '}'
  // console.log(imgFileContent);

  imgFileContent = prettier.format(imgFileContent, { parser: 'babel' });
  fs.writeFileSync(join(configFilePath, 'images.js'), imgFileContent, 'utf8')
}

module.exports = generateConfig;